/*
 * @Author: zhangxin 
 * @Date: 2020-10-15 17:21:01 
 * @Last Modified by: zhangxin
 * @Last Modified time: 2021-02-20 14:29:29
 * 
 * 文件上传组件
 * 上传成功的组件展示在table列表中,可托管form表单
 */


import React, { useState,useEffect,Fragment } from "react";
import { Table, Upload, Popover, message } from "antd";
import hcpUtils from "@/utils/hcpUtils";
import request from "@/utils/request";
import "./index.less"

const HcpUploadTable = (props) => {
    const { 
        extra,  // 额外说明
        columns,  // 表头
        accept, //类型
        size = 10*1024*1024, // 大小
        number, //文件上传数量限制
        action, // 上传地址
        method="post", // 上传方式
        multiple=false, // 上传多选
        value, // 默认值
        onChange,
        ...prop
    } = props;

	const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState(value || []);
	const [fileList, setFileList] = useState([]);
    const [uploadDisabled, setUploadDisabled] = useState(false);


    useEffect(() => {
        if(number &&  tableData.length >= number){
            setUploadDisabled(true);
        }else{
            setUploadDisabled(false);
        }
        if(onChange) onChange(tableData.length > 0 ? tableData : undefined);
    }, [tableData])

    const tableColumns = [
		{
			title: '序号',
            dataIndex: 'sort',
            align: 'center',
            render: (text, record, index) => {
                return index + 1;
            }
		},
		{
			title: '文件名称',
            dataIndex: 'name',
            align: 'center',
		},
		{
			title: '文件大小',
            dataIndex: 'size',
            align: 'center',
            render: (text) => {
                return hcpUtils.bytesToSize(text)
            }
		},

		{
			title: "操作",
            dataIndex: "operation",
            align: 'center',
			render: (text, record, index) => {
				return (
					<div>
						&nbsp;&nbsp;
						<Popover content={"删除"} >
							<span style={{ cursor: 'pointer' }} className="iconfont icon-delete"
								onClick={ () => handleDelete(text,record,index)}
							></span>
						</Popover>
					</div>
				)
			}
		}
    ];
    
    const computeFileList = (file,status) => {
        setFileList((fileList) =>{
            let arr = [];
            fileList.map(item => {
                if(item.uid != file.uid){
                    arr.push(item);
                }
            })
            return arr
        })
    }

    const computeTableData = (res) => {
        let arr = res.fileName.split("."); // 对文件名进行切割
        let prefix = arr.slice(0,arr.length-1).join("."); // 文件前缀
        let suffix = "."+arr[arr.length-1]; // 文件后缀
        let prefixArr = prefix.split("_");
        let rename = prefixArr.slice(0,prefixArr.length-1).join("_")+suffix;
        let obj = {
            name:rename,
            url:res.fileName,
            size:res.size,
        }
        setTableData((data)=>{
            let arr = [...data];
            arr.push(obj);
            arr.forEach((i,index) => (i.key = index));
            return arr;
        })
    }

    const uploadProps = {
		name: 'file',
		action: API_SERVER + action,
        method: method,
        multiple: multiple,
        accept:accept || null,
		headers: {
            // authorization: 'authorization-text',
            ACCESS_TOKEN: hcpUtils.getToken(),
            token: hcpUtils.getToken(),
        },
        disabled:uploadDisabled,
        fileList:fileList,
        onRemove:(file) => {
            computeFileList(file);
            setUploadDisabled(true);
        },
		onChange:async ({file,fileList}) => {
			if (file.status === 'uploading') {
                setLoading(true)
                setFileList(fileList);
                setUploadDisabled(true);
			}
			if (file.status === 'done') {
                setLoading(false)
                computeFileList(file,file.status);
                setUploadDisabled(false);
                let response = file.response
				if (response && response.code == 200) {
                    // 成功处理
                    computeTableData(response)
                    message.success(`${file.name} 上传成功`);
				}else{
				    message.error(response.info);
                }
			} else if (file.status === 'error') {
                // 失败处理
                computeFileList(file,file.status);
                setUploadDisabled(false);
                setLoading(false)
				message.error(`${file.name} 上传失败`);
			}
        },
        beforeUpload: (file,fileList) => {
            if(!action){
                message.error(`上传地址不存在`);
                return false;
            }
            // 数量判断
            if(fileList.length + tableData.length > number){
                message.error(`最多能上传${number}个文件`);
                return false;
            }
            let isAccept=true,isSize=true;
            // 类型判断
            if(accept && typeof accept == 'string'){
                let arrType = accept.split(",");
                let arr = file.name.split(".");
                let suffix = "."+arr[arr.length-1];
                if (arrType.indexOf(file.type) > -1 || arrType.indexOf(suffix) > -1) {
                    isAccept = true;
                }else{
                    message.error(`文件类型不正确`);
                    isAccept = false;
                }
            }else{
                isAccept = true;
            };
            // 大小判断
            if(file.size > size){
                message.error(`文件的大小${hcpUtils.bytesToSize(file.size)},不可超过${hcpUtils.bytesToSize(size)}`);
                isSize = false;
            }else{
                isSize = true;
            };
            return isAccept && isSize;
        },
        ...prop,
	};

    const handleDelete = (text, record, index) => {
        setTableData((data)=>{
            let arr = JSON.parse(JSON.stringify(data));
            arr.splice(index,1);
            return arr;
        })
	};

    return (
        <div className="hcp_upload_table">
            <div className="hcp_upload_div">
                <Upload
                    {...uploadProps}
                >
                    <span className="iconfont icon-on-shelf">
                        上传文件
                    </span>
                </Upload>
                {
                    extra
                }
            </div>
            <Table
                columns={columns || tableColumns}
                loading={loading}
                dataSource={tableData}
                pagination={false}
                style={{ width: "700px" }}
            />
        </div>
    );
};

export default HcpUploadTable;
